<?php
class HTML{
    static $allowedTags = '<h1><b><i><a><ul><li><hr><strong><table><tr><td><h2><span><br><center><ol><p>';
    static $stripAttrib ='javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';

    /**
     * @return string
     * @param string
     * @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
     */
    static function removeEvilTags($source){
        $source = strip_tags(preg_replace( array(
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?>.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<applet[^>]*?.*?</applet>@siu',
            '@<noframes[^>]*?.*?</noframes>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu'
        ), '', $source), HTML::$allowedTags);

        return preg_replace('/<(.*?)>/ie', "'<'.HTML::removeEvilAttributes('\\1').'>'", $source);
    }

    /**
     * @return string
     * @param string
     * @desc Strip forbidden attributes from a tag
     */
    static function removeEvilAttributes($tagSource){
        return stripslashes(preg_replace("/".HTML::$stripAttrib."/i", 'forbidden', $tagSource));
    }

    static function html2txt($document){
        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
            '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
            '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
            '@<![\s\S]*?--[ \t\n\r]*>@',        // Strip multi-line comments including CDATA
            '/\\[([\s]*[0-9]{1,2}[\s]*)\]/eis'  // Strip [1][2][3]
        );
        $text = preg_replace($search, '', $document);
        return $text;
    }


    /*
      * @author : ngannv
      * @Comment: Xóa mã thừa của MS word trong nội dụng tin đăng và xóa một số khối thẻ không cho phép sử dụng
      * @param : $string
      * @return String
      * */
    static function remove_bad_tags($val){
        /*
           * Ngannv Dev Xóa  mã thừa của MS Word khi người dùng paste từ MS Word
           * */
        $val=preg_replace('/(<style>.+?)+(<\/style>)/iusm', '', $val);//xóa định nghĩa style office 2010, (2003, 2007 ?)
        // $val=preg_replace('/(<w:.+?)+(\/>)/iusm', '', $val);//xóa nội dung trong khối W kết thúc bằng /> {#1#}
        //$val=preg_replace('/(<w:.+?)+(>)/iusm', '', $val);//xóa nội dung trong khối W kết thúc bằng > {#2#}
        //{#1#} và {#2#} có thể ko cần thiết vì khối <W: xxx /> nằm trong khối XML sẽ được remove dưới đây
        $val=preg_replace('/(<xml>.+?)+(<\/xml>)/iusm', '', $val);//xóa nội dung trong khối XML
        $val=preg_replace('/(<!--.+?)+(-->)/iusm', '', $val);//Xóa nội dụng trong khối Comment
        /*
           * Tránh hiện tượng nhúng From action , input ,Iframe,frame và Script js , <?php  ?>...vào tin đăng
           * */
        $val=preg_replace("/(<\?.+?)+( ?>)/iusm", '', $val); //Tin đăng có nhúng mã PHP
        $val=preg_replace('/(<form>.+?)+(<\/form>)/iusm', '', $val);//Nội dung tin đăng có nhúng Form->Xóa
        $val=preg_replace('/(&lt;form&gt;.+?)+(&lt;\/form&gt;)/iusm', '', $val);
        $val=preg_replace('/(<form .+?>.+?)+(<\/form>)/iusm', '', $val);//Tin đăng có nhúng Form+thuộc tính form->Xóa
        $val=preg_replace('/(&lt;form .+?&gt;.+?)+(&lt;\/form&gt;)/iusm', '', $val);
        $val=preg_replace('/(<input .+?)+(\/>)/iusm', '', $val);//Tin đăng có nhúng thẻ input->Xóa
        $val=preg_replace('/(<input .+?)+(\>)/iusm', '', $val);
        //$val=preg_replace('/(<meta .+?)+(\>)/iusm', '', $val);//the meta
        //$val=preg_replace('/(<meta .+?)+(>)/iusm', '', $val);
        //$val=preg_replace('/(&lt;meta .+?)+(&gt;)/iusm', '', $val);
        //$val=preg_replace('/(&lt;meta .+?)+(\/&gt;)/iusm', '', $val);
        $val=preg_replace('/(&lt;input .+?)+(\/&gt;)/iusm', '', $val);
        $val=preg_replace('/(&lt;input .+?)+(\&gt;)/iusm', '', $val);
        $val=preg_replace('/(<link .+?)+(\>)/iusm', '', $val);//the link
        $val=preg_replace('/(<link .+?)+(>)/iusm', '', $val);
        $val=preg_replace('/(&lt;link .+?)+(\&gt;)/iusm', '', $val);
        $val=preg_replace('/(&lt;link .+?)+(\/&gt;)/iusm', '', $val);
        $val=preg_replace('/(<script .+?>.+?)+(<\/script>)/iusm', '', $val);//Tin đăng có nhúng script->Xóa
        $val=preg_replace('/(&lt;script .+?&gt;.+?)+(&lt;\/script>&gt;)/iusm', '', $val);
        $val=preg_replace('/(<script>.+?)+(<\/script>)/iusm', '', $val);//Tin đăng có nhúng script->Xóa
        $val=preg_replace('/(&lt;script&gt;.+?)+(&lt;\/script&gt;)/iusm', '', $val);
        $val=preg_replace('/( class=".+?)+( ")/iusm', '', $val);//Tin đăng có nhúng class css
        $val=preg_replace('/(<iframe .+?>.+?)+(<\/iframe>)/iusm', '', $val);//Tin đăng có nhúng iframe->Xóa
        $val=preg_replace('/(<frameset .+?>.+?)+(<\/frameset>)/iusm', '', $val);//Tin đăng có nhúng frame->Xóa
        $val=preg_replace('/(&lt;iframe .+?&gt;.+?)+(&lt;\/iframe&gt;)/iusm', '', $val);
        $val=preg_replace('/(&lt;frameset .+?&gt.+?)+(&lt;\/frameset&gt)/iusm', '', $val);
        /*
           * Các khối thẻ đơn chỉ có mở hoặc chỉ có đóng do người dùng cố tình nhập vào
           * */
        //$val=str_replace('DOCTYPE','',$val);
        // $val=str_replace('<head>','',$val);
        // $val=str_replace('&lt;head&gt;','',$val);
        $val=str_replace('&lt;script&gt;','',$val);
        $val=str_replace('<script>','',$val);
        return $val;
    }

    /**
     * Function replace <br>
     * @author DungNH
     * date create: 24/12/2010
     */
    static function replaceBr($strData){
        return preg_replace('#(&lt;br /&gt;){3,}#', '&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;', $strData);
        //return preg_replace('#(<br>){3,}#', '<br><br><br>', $strData);
    }

    static function getOption($options_array, $selected) {
        $input = '';
        if ($options_array)
            foreach ($options_array as $key => $text) {
                $input .= '<option value="' . $key . '"';
                if ($key === '' && $selected === '') {
                    $input .= ' selected';
                } else
                    if ($selected !== '' && $key == $selected) {
                        $input .= ' selected';
                    }
                $input .= '>' . $text . '</option>';
            }
        return $input;
    }

    static function getOptionMulti($options, $select_array) {
        $input = '';
        if ($options) {
            foreach ($options as $key => $text) {
                $input .= '<option value="' . $key . '"';
                if (in_array($key, $select_array)) {
                    $input .= ' selected';
                }

                $input .= '>' . $text . '</option>';
            }
        }
        return $input;
    }

    static function getOptionNum($min, $max, $default=1) {
        $options = '';
        for ($i = $min; $i <= $max; $i++) {
            $options .= '<option value="';
            if ($i < 10)
                $options .= '0' . $i . '"';
            else
                $options .= $i . '"';
            if ($i == $default) {
                $options .= ' selected';
            }
            $options .= '>' . $i . '</option>';
        }
        return $options;
    }

    static function render_radio_option($name, $options, $checkValue = 0, $id = null, $labelFist = true) {
        $html = '';
        if (is_array($options) && sizeof($options) > 0) {
            foreach ($options as $label => $value) {
                $_option = '<input name="' .$name .'" type="radio" value="' .$value .'"'
                    .((null != $id)? ' id="' .$id .'"' : '')
                    .(($value == $checkValue)? ' checked="checked"' : '') .' />';
                $html .= '<label>'
                    .((false === $labelFist)? $_option .$label : $label.$_option)
                    .'</label>';
            }
        }
        return $html;
    }

    /* ------------------------------------------------------------------------- */

    // Key Cleaner - ensures no funny business with form elements
    /* ------------------------------------------------------------------------- */
    static function clean_key($key) {
        if ($key == "") {
            return "";
        }

        $key = htmlspecialchars(urldecode($key));
        $key = preg_replace("/\.\./", "", $key);
        $key = preg_replace("/\_\_(.+?)\_\_/", "", $key);
        $key = preg_replace("/^([\w\.\-\_]+)$/", "$1", $key);
        return $key;
    }


    static function cleanHtml($aVarName, $aVarAlt="") {
        $lVarName = $aVarName;
        if (!Empty($lVarName)) {
            if (is_array($lVarName)) {
                $lReturnArray = array();
                foreach ($lVarName as $key => $value) {
                    $value = self::clean_value($value);
                    $key = self::clean_key($key);
                    $lReturnArray[$key] = $value;
                }
                return $lReturnArray;
            }
            else
                return self::clean_value($lVarName); // Clean input and return it




        }
        else
            return $aVarAlt;
    }

    /* ------------------------------------------------------------------------- */

    // Clean value
    /* ------------------------------------------------------------------------- */

    static function clean_value($val) {
        $strip_space_chr = 1;
        $get_magic_quotes = @get_magic_quotes_gpc();

        if ($val == "") {
            return "";
        }

        $val = str_replace("&#032;", " ", $val);

        if ($strip_space_chr) {
            $val = str_replace(chr(0xCA), "", $val);  //Remove sneaky spaces
        }
        //$val = str_replace( "&"            , "&amp;"         , $val );
        $val = str_replace("<!--", "", $val); //&#60;&#33;--
        $val = str_replace("-->", "", $val); //--&#62;
        $val = preg_replace("/<script/i", "&#60;script", $val);
        $val = str_replace(">", "&gt;", $val);
        $val = str_replace("<", "&lt;", $val);
        $val = str_replace("\"", "&quot;", $val);
        $val = preg_replace( "/\n/"        , "<br />"        , $val ); // Convert literal newlines
        $val = preg_replace("/\\\$/", "&#036;", $val);
        $val = preg_replace("/\r/", "", $val); // Remove literal carriage returns
        $val = str_replace("!", "&#33;", $val);
        $val = str_replace("'", "&#39;", $val); // IMPORTANT: It helps to increase sql query safety.

        if ($get_magic_quotes) {
            $val = stripslashes($val);
        }

        $val = preg_replace("/\\\(?!&amp;#|\?#)/", "&#092;", $val);

        return $val;
    }

    //-----------------------------------------
    // parse_html
    // Converts the doHTML tag
    //-----------------------------------------
    static function post_db_parse_html($t="") {
        if ($t == "") {
            return $t;
        }

        //-----------------------------------------
        // Remove <br>s 'cos we know they can't
        // be user inputted, 'cos they are still
        // &lt;br&gt; at this point :)
        //-----------------------------------------

        /* 		if ( $this->pp_nl2br != 1 )
          {
          $t = str_replace( "<br>"    , "\n" , $t );
          $t = str_replace( "<br />"  , "\n" , $t );
          } */

        $t = str_replace("&#39;", "'", $t);
        $t = str_replace("&#33;", "!", $t);
        $t = str_replace("&#036;", "$", $t);
        $t = str_replace("&#124;", "|", $t);
        $t = str_replace("&amp;", "&", $t);
        $t = str_replace("&gt;", ">", $t);
        $t = str_replace("&lt;", "<", $t);
        $t = str_replace("&quot;", '"', $t);

        //-----------------------------------------
        // Take a crack at parsing some of the nasties
        // NOTE: THIS IS NOT DESIGNED AS A FOOLPROOF METHOD
        // AND SHOULD NOT BE RELIED UPON!
        //-----------------------------------------

        $t = preg_replace("/javascript/i", "j&#097;v&#097;script", $t);
        $t = preg_replace("/alert/i", "&#097;lert", $t);
        $t = preg_replace("/about:/i", "&#097;bout:", $t);
        $t = preg_replace("/onmouseover/i", "&#111;nmouseover", $t);
        $t = preg_replace("/onmouseout/i", "&#111;nmouseout", $t);
        $t = preg_replace("/onclick/i", "&#111;nclick", $t);
        $t = preg_replace("/onload/i", "&#111;nload", $t);
        $t = preg_replace("/onsubmit/i", "&#111;nsubmit", $t);
        $t = preg_replace("/object/i", "&#111;bject", $t);
        $t = preg_replace("/frame/i", "fr&#097;me", $t);
        $t = preg_replace("/applet/i", "&#097;pplet", $t);
        $t = preg_replace("/meta/i", "met&#097;", $t);
        $t = preg_replace("/embed/i", "met&#097;", $t);

        return $t;
    }

    static function remove_4_js($t) {
        $t = String::make_single_space($t);
//		$t = str_replace( "'","&#39;"  ,  $t );
        $t = str_replace("'", "&quot;", $t);
        $t = str_replace("&#39;", "", $t);
        $t = str_replace("!", "&#33;", $t);
        $t = str_replace("$", "&#036;", $t);
        $t = str_replace("|", "&#124;", $t);
        //$t = str_replace( "&","&amp;"   , $t );
        $t = str_replace(">", "&gt;", $t);
        $t = str_replace("<", "&lt;", $t);
        $t = str_replace('"', "&quot;", $t);
        //$t = str_replace( '"', "&quot;" , $t );

        $t = str_replace(chr(10), "", $t);
        $t = str_replace(chr(13), "", $t);

        return trim($t);
    }

    static function remove_tag($text, $allowtag=""){
        return trim(strip_tags($text, $allowtag));
    }

    static function optArr(&$mData)
    {
        if (is_array($mData)) {
            if (count($mData) == 1) {
                $mData = array_shift($mData);
                if (is_array($mData)) {
                    foreach ($mData as &$aSub) {
                        ECLib::optArr($aSub);
                    }
                }
            } else {
                foreach ($mData as &$aSub) {
                    HTML::optArr($aSub);
                }
            }
        }
        return $mData;
    }

    /*	Ham remove  html va php tag  2
     Chap nhan xu ly nhieu tag array
     */

    static function remove_tag_array($text, $tag_array=""){
        if(is_array($tag_array)){

            //$tag_array = Array("html","body","meta","link","head");

            foreach ($tag_array as $tag) {
                $text = preg_replace("/<\/?" . $tag . "(.|\s)*?>/","",$text);
            }
        }
        return $text;
    }

    //-----------------------------------------
    // parse_html
    // Converts the doHTML tag
    //-----------------------------------------

    static function dohtml($t=""){
        if ( $t == "" ){
            return $t;
        }
        //-----------------------------------------
        // Remove <br>s 'cos we know they can't
        // be user inputted, 'cos they are still
        // &lt;br&gt; at this point :)
        //-----------------------------------------
        if ( $this->pp_nl2br != 1 ){
            $t = str_replace( "<br>"    , "\n" , $t );
            $t = str_replace( "<br />"  , "\n" , $t );
        }

        $t = str_replace( "&#39;"   , "'", $t );
        $t = str_replace( "&#33;"   , "!", $t );
        $t = str_replace( "&#036;"   , "$", $t );
        $t = str_replace( "&#124;"  , "|", $t );
        $t = str_replace( "&amp;"   , "&", $t );
        $t = str_replace( "&gt;"    , ">", $t );
        $t = str_replace( "&lt;"    , "<", $t );
        $t = str_replace( "&quot;"  , '"', $t );

        //-----------------------------------------
        // Take a crack at parsing some of the nasties
        // NOTE: THIS IS NOT DESIGNED AS A FOOLPROOF METHOD
        // AND SHOULD NOT BE RELIED UPON!
        //-----------------------------------------

        $t = preg_replace( "/javascript/i" , "j&#097;v&#097;script", $t );
        $t = preg_replace( "/alert/i"      , "&#097;lert"          , $t );
        $t = preg_replace( "/about:/i"     , "&#097;bout:"         , $t );
        $t = preg_replace( "/onmouseover/i", "&#111;nmouseover"    , $t );
        $t = preg_replace( "/onclick/i"    , "&#111;nclick"        , $t );
        $t = preg_replace( "/onload/i"     , "&#111;nload"         , $t );
        $t = preg_replace( "/onsubmit/i"   , "&#111;nsubmit"       , $t );
        return $t;
    }
}
?>